package com.ruoyi.depot.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.ruoyi.commodity.domain.ProductImage;
import com.ruoyi.commodity.mapper.ProductImageMapper;
import com.ruoyi.common.api.procuredStorage.ProcuredStorageApi;
import com.ruoyi.common.api.procuredStorage.dto.ProcuredStorageDto;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.depot.domain.ProcuredStorageDetail;
import com.ruoyi.depot.domain.vo.DetailedInventoryAgeVO;
import com.ruoyi.depot.mapper.ProcuredStorageDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.depot.domain.InboundProducts;
import com.ruoyi.depot.mapper.ProcuredStorageMapper;
import com.ruoyi.depot.domain.ProcuredStorage;
import com.ruoyi.depot.service.IProcuredStorageService;

/**
 * 采购入库单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-13
 */
@Service
public class ProcuredStorageServiceImpl implements IProcuredStorageService, ProcuredStorageApi {
	@Autowired
	private ProcuredStorageMapper procuredStorageMapper;

	@Autowired
	private ProductImageMapper productImageMapper;

	@Autowired
	private ProcuredStorageDetailMapper procuredStorageDetailMapper;

	/**
	 * 查询采购入库单
	 *
	 * @param storageId 采购入库单主键
	 * @return 采购入库单
	 */
	@Override
	public ProcuredStorage selectProcuredStorageByStorageId(Long storageId) {
		return procuredStorageMapper.selectProcuredStorageByStorageId(storageId);
	}

	/**
	 * 查询采购入库单列表
	 *
	 * @param procuredStorage 采购入库单
	 * @return 采购入库单
	 */
//    @Override
//    public List<ProcuredStorage> selectProcuredStorageList(ProcuredStorage procuredStorage) {
//        // 查询主列表
//        List<ProcuredStorage> procuredStorages = procuredStorageMapper.selectProcuredStorageList(procuredStorage);
//
//        if (procuredStorages == null || procuredStorages.isEmpty()) {
//            return procuredStorages; // 如果主列表为空，直接返回
//        }
//
//        // 批量提取所有需要的 productId
//        Set<Long> productIds = procuredStorages.stream()
//                .flatMap(storage -> storage.getProcuredStorageDetails().stream())
//                .map(ProcuredStorageDetail::getProductId)
//                .collect(Collectors.toSet());
//
//        // 一次性查询所有产品图片
//        Map<Integer, List<String>> productImagesMap = productImageMapper.selectList(
//                        new LambdaQueryWrapper<ProductImage>().in(ProductImage::getProductId, productIds))
//                .stream()
//                .collect(Collectors.groupingBy(
//                        ProductImage::getProductId,
//                        Collectors.mapping(ProductImage::getProductImagePath, Collectors.toList())
//                ));
//
//        // 填充每个存储明细的图片
//        procuredStorages.forEach(storage ->
//                storage.getProcuredStorageDetails().forEach(detail ->
//                        detail.setProductImages(productImagesMap.getOrDefault(detail.getProductId().intValue(), Collections.emptyList()))
//                )
//        );
//
//        return procuredStorages;
//    }
//
	@Override
	public List<ProcuredStorage> selectProcuredStorageList(ProcuredStorage procuredStorage) {
		// 查询入库单
		List<ProcuredStorage> procuredStorages = procuredStorageMapper.selectProcuredStorageList(procuredStorage);
		// 提取入库单id
		List<String> storageIds = procuredStorages.stream().map(ProcuredStorage::getStorageId).collect(Collectors.toList());
		if (!storageIds.isEmpty()) {
			// 根据提取的入库单id查询对应的入库单详细
			List<ProcuredStorageDetail> merged  = procuredStorageDetailMapper.selectDetalis(storageIds);
			List<ProcuredStorageDetail> procuredStorageDetails = mergeDetails(merged);

			// 提取所有 productId
			List<Long> productIds = procuredStorageDetails.stream()
					.map(ProcuredStorageDetail::getProductId)
					.distinct()
					.collect(Collectors.toList());

			// 批量查询所有图片路径
			Map<Integer, List<String>> productImagesGroupedByProductId = productImageMapper.selectProductImagesByProductId(productIds)
					.stream()
					.collect(Collectors.groupingBy(ProductImage::getProductId,
							Collectors.mapping(ProductImage::getProductImagePath, Collectors.toList())));

			// 将图片分配到每个 ProcuredStorageDetail
			procuredStorageDetails.forEach(item -> {
				List<String> imagePath = productImagesGroupedByProductId.getOrDefault(item.getProductId().intValue(), new ArrayList<>());
				item.setProductImages(imagePath);
			});


			// 按照入库单 ID 分组入库单详细数据
			Map<String, List<ProcuredStorageDetail>> detailsGroupedByStorageId = procuredStorageDetails.stream()
					.collect(Collectors.groupingBy(ProcuredStorageDetail::getStorageId));

			// 将分组的详细数据分配到对应的入库单
			procuredStorages.forEach(storage -> {
				List<ProcuredStorageDetail> details = detailsGroupedByStorageId.getOrDefault(storage.getStorageId(), new ArrayList<>());
				storage.setProcuredStorageDetails(details);
			});
		}

		return procuredStorages;
	}

	/**
	 * 按 storageId + productId 分组，累加数量和货值，拼接备注
	 */
	public List<ProcuredStorageDetail> mergeDetails(List<ProcuredStorageDetail> list) {
		// 用 Map 保证同一 key 只有一个对象
		Map<String, ProcuredStorageDetail> map = new LinkedHashMap<>();

		for (ProcuredStorageDetail d : list) {
			String key = d.getStorageId() + "_" + d.getProductId();
			if (!map.containsKey(key)) {
				// 第一次出现，拷贝一个新实例，清零数值字段，初始化备注和值
				ProcuredStorageDetail copy = new ProcuredStorageDetail();
				BeanUtils.copyProperties(d, copy);

				// 初始化累加字段
				copy.setActualQuantity(d.getActualQuantity());
				copy.setGoodQuantity(d.getGoodQuantity());
				copy.setDefectiveQuantity(d.getDefectiveQuantity());
				// 初始化 gtins 列表
				copy.setGtins(new ArrayList<>());
				copy.getGtins().add(d.getGtin());

				// 备注可能为空，防 NPE
				copy.setRemark(d.getRemark() == null ? "" : d.getRemark());

				map.put(key, copy);
			} else {
				// 已存在，累加各字段
				ProcuredStorageDetail exist = map.get(key);

				exist.setActualQuantity(exist.getActualQuantity() + d.getActualQuantity());
				exist.setGoodQuantity(exist.getGoodQuantity() + d.getGoodQuantity());
				exist.setDefectiveQuantity(exist.getDefectiveQuantity() + d.getDefectiveQuantity());

				// 备注拼接，用分号分隔
				String rem = exist.getRemark();
				if (d.getRemark() != null && !d.getRemark().isEmpty()) {
					rem = rem.isEmpty() ? d.getRemark() : rem + ";" + d.getRemark();
					exist.setRemark(rem);
				}
				// 收集 gtin
				exist.getGtins().add(d.getGtin());
			}
		}

		// 返回合并后的结果列表
		return new ArrayList<>(map.values());
	}


//	public List<ProcuredStorageDetail> mergeWithStreams(List<ProcuredStorageDetail> details) {
//		return details.stream()
//				// 先分组：key 是 storageId + "|" + productId
//				.collect(Collectors.groupingBy(
//						d -> d.getStorageId() + "|" + d.getProductId()
//				))
//				.values().stream()
//				.map(list -> {
//					// 对每个分组做汇总
//					ProcuredStorageDetail first = list.get(0);
//					ProcuredStorageDetail agg   = new ProcuredStorageDetail();
//					BeanUtils.copyProperties(first, agg,
//							"goodQuantity", "defectiveQuantity", "actualQuantity",
//							"value", "inboundCost");
//
//					// 数量累加
//					int totalActual = list.stream().mapToInt(ProcuredStorageDetail::getActualQuantity).sum();
//					int totalGood   = list.stream().mapToInt(ProcuredStorageDetail::getGoodQuantity).sum();
//					int totalDef    = list.stream().mapToInt(ProcuredStorageDetail::getDefectiveQuantity).sum();
//
//					agg.setActualQuantity(totalActual);
//					agg.setGoodQuantity(totalGood);
//					agg.setDefectiveQuantity(totalDef);
//
//					// 货值 & 成本累加
//					BigDecimal totalValue = list.stream()
//							.map(d -> d.getPrice().multiply(BigDecimal.valueOf(d.getActualQuantity())))
//							.reduce(BigDecimal.ZERO, BigDecimal::add);
//					BigDecimal totalCost  = list.stream()
//							.map(d -> d.getSingleProductCost().multiply(BigDecimal.valueOf(d.getActualQuantity())))
//							.reduce(BigDecimal.ZERO, BigDecimal::add);
//
//					agg.set(totalValue);
//					agg.setInboundCost(totalCost);
//
//					return agg;
//				})
//				.collect(Collectors.toList());
//	}


//    /**
//     * 新增采购入库单
//     *
//     * @param procuredStorageList 采购入库单
//     * @return 结果
//     */
//    @Transactional
//    @Override
//    public int insertProcuredStorage(List<ProcuredStorage> procuredStorageList)
//    {
//        int rows = procuredStorageMapper.insertProcuredStorage(procuredStorageList);
//        for (ProcuredStorage procuredStorage:procuredStorageList) {
//            insertInboundProducts(procuredStorage);
//        }
//
//        return rows;
//    }

	/**
	 * 修改采购入库单
	 *
	 * @param procuredStorage 采购入库单
	 * @return 结果
	 */
	@Transactional
	@Override
	public int updateProcuredStorage(ProcuredStorage procuredStorage) {
//        procuredStorage.setUpdateTime(DateUtils.getNowDate());
//        procuredStorageMapper.deleteInboundProductsByStorageId(procuredStorage.getStorageId());
//        insertInboundProducts(procuredStorage);
//        return procuredStorageMapper.updateProcuredStorage(procuredStorage);
		return 0;
	}

	/**
	 * 批量删除采购入库单
	 *
	 * @param storageIds 需要删除的采购入库单主键
	 * @return 结果
	 */
	@Transactional
	@Override
	public int deleteProcuredStorageByStorageIds(Long[] storageIds) {
		procuredStorageMapper.deleteInboundProductsByStorageIds(storageIds);
		return procuredStorageMapper.deleteProcuredStorageByStorageIds(storageIds);
	}

	/**
	 * 删除采购入库单信息
	 *
	 * @param storageId 采购入库单主键
	 * @return 结果
	 */
	@Transactional
	@Override
	public int deleteProcuredStorageByStorageId(Long storageId) {
		procuredStorageMapper.deleteInboundProductsByStorageId(storageId);
		return procuredStorageMapper.deleteProcuredStorageByStorageId(storageId);
	}

	@Override
	public List<DetailedInventoryAgeVO> getDetailedInventoryAge(DetailedInventoryAgeVO vo) {
		// 检查参数是否为空
		if (vo.getProductId() == null) {
			throw new ServiceException("缺少必要查询参数");
		}

		// 查询入库详细数据
		List<DetailedInventoryAgeVO> detailedInventoryAge = procuredStorageDetailMapper.getDetailedInventoryAge(vo);

		// 提取 productIds
		List<Long> productIds = detailedInventoryAge.stream()
				.map(DetailedInventoryAgeVO::getProductId)
				.collect(Collectors.toList());

		// 防护：如果没有数据，直接返回空列表
		if (productIds.isEmpty() || detailedInventoryAge.isEmpty()) {
			return new ArrayList<>();
		}

		// 查询图片数据并按 productId 分组
		Map<Integer, List<String>> collect = productImageMapper.selectProductImagesByProductId(productIds)
				.stream()
				.collect(Collectors.groupingBy(ProductImage::getProductId,
						Collectors.mapping(ProductImage::getProductImagePath, Collectors.toList())));

		// 将图片数据分配到每个入库详细
		detailedInventoryAge.forEach(item -> {
			List<String> imagePath = collect.getOrDefault(item.getProductId().intValue(), new ArrayList<>());
			item.setProductImages(imagePath);
		});

		return detailedInventoryAge;
	}

	/**
	 * 新增入库产品信息
	 *
	 * @param procuredStorage 采购入库单对象
	 */
	public void insertInboundProducts(ProcuredStorage procuredStorage) {
//        List<InboundProducts> inboundProductsList = procuredStorage.getInboundProductsList();
//        Long storageId = procuredStorage.getStorageId();
//        if (StringUtils.isNotNull(inboundProductsList))
//        {
//            List<InboundProducts> list = new ArrayList<InboundProducts>();
//            for (InboundProducts inboundProducts : inboundProductsList)
//            {
//                inboundProducts.setStorageId(storageId);
//                list.add(inboundProducts);
//            }
//            if (list.size() > 0)
//            {
//                procuredStorageMapper.batchInboundProducts(list);
//            }
//        }
	}
	/**
	 * 根据采购单查询仓库
	 *
	 * @param ordersId
	 */
	@Override
	public ProcuredStorageDto selectWarehouseIdByOrdersId(Long ordersId) {
		return procuredStorageMapper.selectWarehouseIdByOrdersId(ordersId);
	}
}
